﻿using LogSystem;
using Unity.Mathematics;
using UnityEngine;

namespace Yoozoo.Gameplay.RTS
{
    /// <summary>
    ///     当前所在的线段，用于计算当前的位置
    /// </summary>
    public struct Segment
    {

        public long _uid;
     
        public float3 serverPosition;

        public float3 clientPosition;

        public float3 startPosition;

        public float3 endPosition;

        public float3 _caculeStartPosition;

        public float speed;
        
        public float elapsedTime;
        
        public float duration;
        public bool NeedSyncToMarchData;
        public float startTime;
        public float endTime;
        public bool IsBattleMarch;

        public float3 direction;

        public float attackRange;

        public Vector3 segmentStartPosition;

        public Vector3 attackTargetPosition;
        public float attackTargetSpeedTime;
        private float maxCorrectDistance;
        public bool isLastSegment;
        private float attackRangeTime;

        public bool Valid()
        {
            return _uid != 0;
        }

        public void Clear()
        {
            _uid = 0;
            clientPosition = Vector3.zero;
            serverPosition = Vector3.zero;
            elapsedTime = 0;
            duration = 0;
            endPosition = Vector3.zero;
            startPosition = Vector3.zero;
        }
        
        public void UpdateAttackPosition(Vector3 position,float speedTime)
        {
            attackTargetPosition = position;
            attackTargetSpeedTime = speedTime;
            if (isLastSegment && attackTargetPosition != Vector3.zero)
            {
                endPosition = attackTargetPosition;
            }
        }

        public void ClearAttackPosition()
        {
            attackTargetPosition = Vector3.zero;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="currentPosition"></param>
        /// <param name="startPosition">该路段的起始点</param>
        /// <param name="endPosition">该路段的结束点</param>
        /// <param name="speed">行军速度m/s</param>
        /// <param name="lastServerTime"></param>
        public void UpdateInfo(Vector3 currentPosition, Vector3 startPosition, Vector3 endPosition, float speed,
            long lastServerTime,bool isLastSegment,bool IsBattleMarch)
        {
            // TODO: 如果是攻击最后一段行军路线，如果检测到当前位置已经走过了，不再回退
           // Debug.LogErrorFormat($"{_uid} [{Time.frameCount}]Segment.UpdateInfo: current: {currentPosition} ({startPosition} -> {endPosition})");
            this.IsBattleMarch = IsBattleMarch;
            serverPosition = currentPosition;
            clientPosition = currentPosition;
            this.startPosition = startPosition;
            this.endPosition = endPosition;

            this.speed = speed;
  
            // this.lastServerTime = lastServerTime;
            this.isLastSegment = isLastSegment;
            _caculeStartPosition = currentPosition;
            var distance = math.distance(_caculeStartPosition, this.endPosition);
            if (distance >= 0)
            {
                direction = math.normalizesafe(this.endPosition - this.startPosition, float3.zero);
            }

            if (speed == 0)
                duration = 0;
            else
                duration = (distance / this.speed);

            elapsedTime = 0;
            startTime = TimeUtils.GetClientTickTime();  //Segment的开始点是从当前点算的，不是该线段的起始点
            endTime = startTime + duration;
            if (attackRange > 0)
            {
                setAttackRange(attackRange);
            }

            segmentStartPosition = serverPosition;

            this.NeedSyncToMarchData = true;//
            /*if (_uid == MarchSequareConstant.DebugUid.ToString())
            {
                Debug.Log(LogModule.RTS,$"{_uid}-0 UpdateSegments  frameCount： {Time.frameCount}  current: {currentPosition} ({startPosition} -> {endPosition})" );
            }*/
        }

        public void UpdateCurrentPosition(Vector3 currentPos)
        {
            clientPosition = currentPos;
            serverPosition = currentPos;
            endPosition = currentPos;
            startPosition = currentPos;
        }
        

        public void setAttackRange(float ar)
        {
            attackRange = ar;
            if (isLastSegment && IsBattleMarch && speed>0)
            {
                attackRangeTime = attackRange / speed;
                attackTargetPosition = endPosition - direction * attackRange * 0.01f;
                //endPosition = attackTargetPosition;
            }
            else
            {
                attackRangeTime = 0;
            }
        }
        public bool Inited { get; set; }

        public void Calculate(float Timestamp)
        {
            
            /*if (_uid == MarchSequareConstant.DebugUid.ToString())
            {
                Debug.Log(LogModule.RTS,$"{_uid}-0 Calculate  frameCount： {Time.frameCount} Timestamp: {Timestamp}  endTime: {endTime} " );
            } */
            // 计算服务器位置
            if (Timestamp >= endTime)
            {
                serverPosition = endPosition;
                clientPosition = endPosition;
                
                duration = 0; //如果时间到了就将时间间隔置为0，目前marchEntity会在CheckNeedRefreshSegmentStartTime中通过该值判读是否要刷新时间
            }
            else
            {
                var deltaTime = endTime - Timestamp;
                var deltaDistance = speed * deltaTime;
                var speedModifier = 1.0f;
                // 攻击行军快到攻击点时，客户端减速，避免战斗时客户端位置走过攻击点
                if (this.isLastSegment && IsBattleMarch && (elapsedTime+attackRangeTime)>=duration)
                {
                    //speedModifier = 0.1f;
                }
                //serverPosition = serverPosition + deltaDistance * speedModifier * direction;
                if (duration == 0)//防止Duration 为0 造成Lerp结果为NAN
                {
                    serverPosition = _caculeStartPosition;
                }
                else
                {
                    serverPosition = Vector3.Lerp(endPosition, _caculeStartPosition, deltaTime / duration);
                }


                //注掉，简化逻辑，看下后面是否有跳的问题

                // // 计算服务器与客户端位置的差距
                // var distance = math.distance(serverPosition, clientPosition);
                // var clientDeltaDistance = deltaTime * speed;
                //
                // // 如果客户端位置和服务器位置偏差不大，则加速弥补这个偏差；如果偏差过大，直接使用服务器位置
                // if (speedModifier >= 1 && speed > 0 && distance > 2 * clientDeltaDistance && distance < maxCorrectDistance)
                // {
                //     clientPosition = distance + 2 * clientDeltaDistance;
                // }
                // else
                // {
                clientPosition = serverPosition;
                //}
                /*if (_uid == MarchSequareConstant.DebugUid.ToString())
                {
                    Debug.Log(LogModule.RTS,$"{_uid}-0 Calculate  frameCount： {Time.frameCount} elapsedTime: {elapsedTime}  duration: {duration} clientPosition = {clientPosition} " );
                } */
            }
        }

        // private float GetSpeedModifier()
        // {
        //     // 攻击行军快到攻击点时，客户端减速，避免战斗时客户端位置走过攻击点
        //     if (!isInBattle) return 1.0f;
        //     if (enemyPosition.Equals(float3.zero)) return 1.0f;
        //
        //     if (math.abs(serverPosition.x - enemyPosition.x) < attackRange &&
        //         math.abs(serverPosition.z - enemyPosition.z) < attackRange)
        //         return 0.75f;
        //
        //     return 1.0f;
        // }
    }
}
